package com.gjy.netty.ag.n1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-05-18 09:00:12
 */
public class TimeClient {

    private static final Logger logger = LoggerFactory.getLogger(TimeClient.class);

    public static void main(String[] args) {

        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            Bootstrap client = new Bootstrap();
            client.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new TimeClientHandler());
                        }
                    });
            ChannelFuture channelFuture = client.connect("localhost", 8000).sync();
            channelFuture.addListener(future -> {
                if (future.isSuccess()) {
                    logger.info("connect {}:{}", "localhost", 8000);
                } else {
                    logger.error("connect {}:{} fail", "localhost", 8000);
                }
            }).channel().closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            workGroup.shutdownGracefully();
        }
    }

    private static final class TimeClientHandler extends ChannelInboundHandlerAdapter {

        private final ByteBuf message;

        public TimeClientHandler() {
            byte[] req = "query time order".getBytes();
            message = Unpooled.buffer(req.length);
            message.writeBytes(req);
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(message);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            byte[] req = new byte[buf.readableBytes()];
            buf.writeBytes(req);

            String s = new String(req);
            logger.info("now is: {}", s);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            logger.error("cause: {}", cause.getMessage());
            ctx.close();
        }
    }
}
